<template>
  <div class="app-container">
    <el-form :model="forms" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="负责人名称" prop="requireTotalPrices">-->
<!--        <el-input-->
<!--          v-model="forms.assigneeName"-->
<!--          placeholder="请输入"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="供应商">
        <el-select v-model="supplierId" placeholder="请选择供应商">
          <el-option v-for="i in suppliers" :label="i.supplierName" :value="i.supplierId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['storage:purchaseRequire:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['storage:purchaseRequire:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['storage:purchaseRequire:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['storage:purchaseRequire:export']"
        >导出</el-button>
        <el-button
            plain
            @click="handlePurchase"
        >采购</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getListRequire"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseRequireList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id">
        <template #default="scope">
          <span>{{ scope.$index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="skuName" />
      <el-table-column label="预警值" align="center" prop="forewarningSum" />
      <el-table-column label="库存剩余数量" align="center" prop="stock" />
      <el-table-column label="仓库名称" align="center" prop="name" />
      <el-table-column label="采购数量" align="center" prop="requireSum" />
      <el-table-column label="总价" align="center" prop="requireTotalPrices" />
      <el-table-column label="状态" align="center" prop="requireStates">
        <template #default="scope">
          <el-tag v-if="scope.row.requireStates === 1" type="danger">待采购</el-tag>
          <el-tag v-else-if="scope.row.requireStates === 2" type="success">采购中</el-tag>
          <el-tag v-else-if="scope.row.requireStates === 3" type="danger">驳回</el-tag>
          <el-tag v-else-if="scope.row.requireStates === 4" type="primary">已采购</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" v-if="scope.row.requireStates === 1" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['storage:purchaseRequire:edit']">编辑采购信息</el-button>
<!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['storage:purchaseRequire:remove']">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getListRequire"
    />

    <!-- 添加或修改采购需求对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="purchaseRequireRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="采购数量" prop="requireSum">
          <el-input v-model="form.requireSum" placeholder="请输入采购数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PurchaseRequire">
import {
  listPurchaseRequire,
  getPurchaseRequire,
  delPurchaseRequire,
  addPurchaseRequire,
  updatePurchaseRequire,
  listRequire, listSupplier
} from "@/api/storage/purchaseRequire";
import {purchaseAdd} from "@/api/storage/purchase.js";

const { proxy } = getCurrentInstance();

const purchaseRequireList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const supplierId = ref(null);
const requireTotalPrices = ref(null);
const suppliers = ref([]);
const insertPurchase = ref({
  requirementList : [],
  supplierId : 0,
  requireTotalPrices :0
})
const forms = ref({
  assigneeName:'',
  startTime:null,
  endTime:null
})
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    requireTotalPrices: null,
    requireStates: null
  },
  rules: {
  }
});
const datas = ref({
  skuIds: '0',
  skuName: null
})
const { queryParams, form, rules } = toRefs(data);
//
// /** 查询采购需求列表 */
// function getList() {
//   loading.value = true;
//   listPurchaseRequire(queryParams.value).then(response => {
//     purchaseRequireList.value = response.data.rows;
//     total.value = response.data.total;
//     loading.value = false;
//   });
// }


/** 查询采购需求列表 */
function getListRequire() {
  console.log(datas.value)
  listRequire(datas.value).then(response => {
    purchaseRequireList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 查询供应商 */
function getListSupplier() {

  listSupplier(null).then(response => {
    suppliers.value = response.data.rows;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    supplierId: 0,
    skuName: null,
    requireId: null,
    wareSkuId: null,
    requireSum: null,
    requireTotalPrices: null,
    requireStates: null
  };
  proxy.resetForm("purchaseRequireRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  datas.value.skuIds = "0";
  suppliers.value.forEach(item=>{

    if (item.supplierId === supplierId.value){
      datas.value.skuIds += ","+item.skuId
    }
  })
  datas.value.skuIds = datas.value.skuIds.substring(2)
  queryParams.value.pageNum = 1;
  getListRequire();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  insertPurchase.value.requirementList = selection
  console.log(insertPurchase.value)
  ids.value = selection.map(item => item.requireId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加采购需求";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value = row
  console.log(row)
  open.value = true;
}

/** 提交按钮 */
function submitForm() {
  updatePurchaseRequire(form.value).then(response => {
    proxy.$modal.msgSuccess("修改成功");
    open.value = false;
    getListRequire();
  });
  // getPurchaseRequire(form.value).then(response => {
  //   getList();
  //   form.value = response.data;
  //   open.value = true;
  //   title.value = "修改采购需求";
  // });
  // proxy.$refs["purchaseRequireRef"].validate(valid => {
  //   if (valid) {
  //     if (form.value.requireId != null) {
  //       updatePurchaseRequire(form.value).then(response => {
  //         proxy.$modal.msgSuccess("修改成功");
  //         open.value = false;
  //         getList();
  //       });
  //     } else {
  //       addPurchaseRequire(form.value).then(response => {
  //         proxy.$modal.msgSuccess("新增成功");
  //         open.value = false;
  //         getList();
  //       });
  //     }
  //   }
  // });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _requireIds = row.requireId || ids.value;
  proxy.$modal.confirm('是否确认删除采购需求编号为"' + _requireIds + '"的数据项？').then(function() {
    return delPurchaseRequire(_requireIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('storage/purchaseRequire/export', {
    ...queryParams.value
  }, `purchaseRequire_${new Date().getTime()}.xlsx`)
}
/** 采购清单 */
function handlePurchase() {
  if (supplierId.value !=null && supplierId.value > 0 && insertPurchase.value.requirementList.length > 0){
    insertPurchase.value.supplierId = supplierId.value
    if (insertPurchase.value.requirementList.length > 1) {
      for (let i = 0; i < insertPurchase.value.requirementList.length; i++) {
        insertPurchase.value.requireTotalPrices = insertPurchase.value.requireTotalPrices+insertPurchase.value.requirementList[i].requireTotalPrices
      }
    }else {
      insertPurchase.value.requireTotalPrices = insertPurchase.value.requirementList[0].requireTotalPrices
    }
    purchaseAdd(insertPurchase.value).then(item=>{
      proxy.$modal.msgSuccess("采购成功");
      getListRequire();
    })
  }else {
    alert("需选择供应商与商品")
  }

}


getListRequire();
getListSupplier();
</script>
